<template>
  <el-form
    ref="login"
    :model="user"
    :rules="rules"
    label-width="120px"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="user.userName" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="pwd">
      <el-input v-model="user.pwd" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="userLogin"
        >登录</el-button
      >
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { userLogin } from '@a/login'
export default {
  name: 'LoginPage',
  data () {
    return {
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必须填写'
          },
          {
            pattern: /^[a-zA-Z]\w{3,7}$/,
            message: '用户名由4-8位数字字母下划线组成,必须字母开头'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必须填写'
          }
        ]
      },
      user: {
        userName: '',
        pwd: ''
      }
    }
  },
  methods: {
    userLogin () {
      // 用户登录
      this.$refs.login.validate().then(() => {
        // 提交
        userLogin(this.user).then(res => {
          if (res.data.code === 200) {
            const { token, userInfo, role } = res.data.data
            // 立即缓存 为了 持久化
            localStorage.setItem('token', token)
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            localStorage.setItem('role', role)
            // 存储到vuex中
            this.$store.commit('user/INIT_USER_INFO', res.data.data)
            this.$message({
              type: 'success',
              message: '登录成功',
              duration: 1500,
              onClose: () => {
                this.$router.replace('/dashBoard')
              }
            })
          }
        })
      })
    },
    resetForm () {
      // 重置表单
      this.$refs.login.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
